<?php

namespace App\Http\Controllers\Entity\Pm;

use App\Http\Controllers\Controller;
use App\Http\Requests\Entity\Pm\MeteringPeriodRequest;
use App\Models\Entity\Pm\ExpiryDate;
use App\Models\Entity\Pm\MeteringPeriod;
use App\Repositories\Entity\Pm\MeteringPeriodRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Response;
use Validator;

class MeteringPeriodController extends Controller
{
    use ModelForm;

    /** @var  MeteringPeriodRepository */
    private $meteringPeriodRepository;

    public function __construct(MeteringPeriodRepository $meteringPeriodRepo)
    {
        $this->meteringPeriodRepository = $meteringPeriodRepo;
    }

    /**
     * Display a listing of the MeteringPeriod.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.pm.metering_periods.index_header'));
            $content->description(__('entity.pm.metering_periods.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new MeteringPeriod.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.pm.metering_periods.create_header'));
            $content->description(__('entity.pm.metering_periods.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created MeteringPeriod in storage.
     *
     * @param MeteringPeriodRequest $request
     *
     * @return Response
     */
    public function store(MeteringPeriodRequest $request)
    {
        $input = $request->all();

        $meteringPeriod = $this->meteringPeriodRepository->create($input);

        Flash::success(__('entity.pm.metering_periods.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.pm.metering_periods.index'));

    }

    /**
     * Display the specified MeteringPeriod.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $meteringPeriod = $this->meteringPeriodRepository->findWithoutFail($id);

        if (empty($meteringPeriod)) {
            Flash::error(__('entity.pm.metering_periods.not_found'));

            return redirect(route('entity.pm.metering_periods.index'));
        }

        return view('entity.pm.metering_periods.show')->with('meteringPeriod', $meteringPeriod);

    }

    /**
     * Show the form for editing the specified MeteringPeriod.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('entity.pm.metering_periods.edit_header'));
            $content->description(__('entity.pm.metering_periods.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified MeteringPeriod in storage.
     *
     * @param  int              $id
     * @param MeteringPeriodRequest $request
     *
     * @return Response
     */
    public function update($id, Request $request)
    {
        $meteringPeriod = $this->meteringPeriodRepository->findWithoutFail($id);

        if (empty($meteringPeriod)) {
            Flash::error(__('entity.pm.metering_periods.not_found'));

            return redirect(route('entity.pm.metering_periods.index'));
        }
        $sValidators = [
            'name'           => 'required|max:100',
            'title'          => 'max:100',
            'short_desc'     => 'required|max:100',
            'unit'           => 'required|max:100',
            'amount'         => 'required|integer',
            'expiry_date_id' => 'required_if:unit,7',
        ];

        $validators = [];

        $input = $request->all();

        // 判断是否行内编辑
        $input = $this->handleEditable($input);

        // 动态判断校验
        foreach ($input as $key => $value) {
            if (isset($sValidators[$key])) {
                $validators[$key] = $sValidators[$key];
            }
        }

        // 定义校验, 没有移到request
        $validator = Validator::make($input, $validators, [
            'required_if' => '当单位为"次"时, 按次有效期不能为空',
        ], [
            'name'           => '名称',
            'title'          => '标题',
            'subtitle'       => '副标题',
            'short_desc'     => '描述',
            'unit'           => '单位',
            'expiry_date_id' => '按次有效期',
        ]
        );

        // 校验
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        // 排序
        if ($this->handleOrderable($id, $input)) {
            return response([
                'status'  => true,
                'message' => trans('admin::lang.update_succeeded'),
            ]);
        }
        $meteringPeriod = $this->meteringPeriodRepository->update($input, $id);

        Flash::success(__('entity.pm.metering_periods.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.pm.metering_periods.index'));
    }

    /**
     * Remove the specified MeteringPeriod from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->meteringPeriodRepository->batchDelete('id', $id)) {
                return response()->json(['message' => __('entity.pm.metering_periods.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $meteringPeriod = $this->meteringPeriodRepository->findWithoutFail($id);

        if (empty($meteringPeriod)) {
            Flash::error(__('entity.pm.metering_periods.not_found'));

            return redirect(route('entity.pm.metering_periods.index'));
        }

        if ($flag = $this->meteringPeriodRepository->delete($id)) {

            return response()->json(['message' => __('entity.pm.metering_periods.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(MeteringPeriod::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('name', '计费规则名')->help('必填');
            $form->text('title', '标题');
            $form->text('subtitle', '副标题');
            $form->text('short_desc', '描述')->help('必填');
            $form->select('unit', '单位')->options(array(
                1 => '小时',
                2 => '日',
                3 => '年',
                4 => '月',
                5 => '季',
                6 => '周',
                7 => '次',
                8 => '分钟',
            ))->default('1');

            $form->number('amount', '数量');
            $ExpiryDates = ExpiryDate::pluck('name', 'id')->toArray();

            $form->select('expiry_date_id', '按次有效时间')->options(['' => '选择'] + $ExpiryDates);

            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(MeteringPeriod::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // //添加按钮
            // if (!\Gate::check('entity.pm.metering_periods.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     //编辑按钮
            //     if (!\Gate::check('entity.pm.metering_periods.edit')) {
            //         $actions->disableEdit();
            //     }
            //     //删除按钮
            //     if (!\Gate::check('entity.pm.metering_periods.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // //导出按钮
            // if (!\Gate::check('entity.pm.metering_periods.export')) {
            //     $grid->disableExport();
            // }

            // //批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         //批量删除按钮
            //         if (!\Gate::check('entity.pm.metering_periods.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            //添加按钮
            if (Admin::user()->cannot('entity.pm.metering_periods.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                //编辑按钮
                if (Admin::user()->cannot('entity.pm.metering_periods.edit')) {
                    $actions->disableEdit();
                }
                //删除按钮
                if (Admin::user()->cannot('entity.pm.metering_periods.destroy')) {
                    $actions->disableDelete();
                }
            });

            //导出按钮
            if (Admin::user()->cannot('entity.pm.metering_periods.export')) {
                $grid->disableExport();
            }

            //批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    //批量删除按钮
                    if (Admin::user()->cannot('entity.pm.metering_periods.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '计费规则名')->sortable()->editable();
            $grid->column('title', '标题')->sortable()->editable();
            $grid->column('subtitle', '副标题')->sortable()->editable();
            $grid->column('short_desc', '描述')->sortable();
            $grid->column('unit', '单位')->select(array(
                1 => '小时',
                2 => '日',
                3 => '年',
                4 => '月',
                5 => '季',
                6 => '周',
                7 => '次',
                8 => '分钟',
            ));
            $grid->column('amount', '数量')->sortable();
            $grid->column('expiryDate.name', '按次有效时间')->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                // $filter->disableIdFilter();
                // 名称
                $filter->like('name', '名称');
                // 标题
                $filter->like('title', '标题');
                // 数量
                $filter->between('amount', '数量');
            });
        });
    }
}
